﻿using System;
using System.Collections.Generic;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Search;

namespace HeroldIT.Dnn.Modules.News
{
    public class NewsListController : NewsController, ISearchable
    {
        #region ISearchable

        public SearchItemInfoCollection GetSearchItems(ModuleInfo moduleInfo)
        {
            try
            {
                NewsListSettingsProvider module = new NewsListSettingsProvider(moduleInfo);
                this.Module = module;
                SearchItemInfoCollection result = new SearchItemInfoCollection();
                IList<string> locales = this.GetLocales();
                foreach (string locale in locales)
                {
                    string moduleTitle = Localizer.GetLocalizedModule(moduleInfo, locale).ModuleTitle;
                    PagedList<NewsEntry> entries = this.ReadNewsEntries(locale, 0,
                                                                        this.GetMaxCurrentItems());
                    foreach (NewsEntry entry in entries)
                    {
                        string title = moduleTitle + " - " + entry.Details[0].Headline;
                        string content = entry.Details[0].TeaserText;
                        if (!String.IsNullOrEmpty(entry.Details[0].DetailText))
                        {
                            content += " " + entry.Details[0].DetailText;
                        }
                        string description =
                            (locales.Count > 1 ? "[" + locale + "] " : String.Empty)
                            + HtmlUtils.Shorten(
                                  HtmlUtils.Clean(
                                      HttpUtility.HtmlDecode(entry.Details[0].TeaserText),
                                      false),
                                  200, "...");
                        SearchItemInfo info = new SearchItemInfo(title, description, Null.NullInteger,
                                                                 entry.DisplayDate, this.ModuleId,
                                                                 "NewsEntryId:" + entry.NewsEntryId, content);
                        result.Add(info);
                    }
                }
                return result;
            }
            catch (Exception e)
            {
                Exceptions.LogException(e);
            }
            return new SearchItemInfoCollection();
        }

        #endregion
    }
}
